from fastapi.requests import Request
from pydantic import conint

from utils.drivers.database.models.product import Product
from utils.exception import AppException, StatusCode
from utils.pagination import get_pagination
from utils.template.template import template


async def search(request: Request, q: str, page: conint(ge=1) = 1):
    if not q:
        raise AppException(code=StatusCode.SearchKeywordEmpty)

    search_products_result, products_count = await Product.get(name=q, page=page, page_size=12)
    search_products_result = [p.model(request.state.language) for p in search_products_result]

    pagination = get_pagination(page, 12, products_count)

    return template(request, "search.html", context={
        "nav": "index",
        "keyword": q,
        "search_products_result": search_products_result,
        "pagination": pagination,
    })
